package com.ym.controller.financialManagement;

import com.github.pagehelper.PageInfo;

import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.exception.BusinessException;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.utils.excel.ExportExcelUtil;
import com.ym.core.utils.tkmybatis.TK;

import com.ym.medical.domain.entity.PlatformAccountEntity;
import com.ym.medical.domain.entity.PlatformTradeDetailEntity;
import com.ym.medical.domain.entity.SysDrawEntity;
import com.ym.medical.domain.param.PlatformAccountExampleParam;
import com.ym.medical.domain.param.PlatformTradeDetailParam;
import com.ym.medical.domain.param.SysAuditParam;
import com.ym.medical.domain.vo.SysAuditVo;
import com.ym.medical.domain.vo.TdDetailSummaryVO;
import com.ym.medical.enums.CashFlowEnum;
import com.ym.medical.enums.TransactionDetailsTdTypeEnum;
import com.ym.medical.service.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "平台账户管理")
@RestController
@RequestMapping("/platformAccountManagement")
@Validated
public class PlatformAccountManagement extends BaseController {

	@Autowired
	private IPlatformAccountSV platformAccountSV;
	@Autowired
	private IPlatformTradeDetailSV platformTradeDetailSV;
	@Autowired
	private ISysAuditSV sysAuditSV;
	@Autowired
	private ISysDrawSV sysDrawSV;
	@Autowired
	private IConsumeDetailsSV consumeDetailsSV;
	@Autowired
	private ITransactionDetailsSV transactionDetailsSV;

	@ApiOperation("平台账户交易明细")
	@GetMapping(value = "/tdDetail/list")
	public APIResponse<PageInfo<PlatformTradeDetailEntity>> listPlatformTdDetail(
			PlatformTradeDetailParam platformTradeDetailModel,
			@RequestParam(defaultValue = "1") int pageNo,
			@RequestParam(defaultValue = "10") int limit
	) {
		return successData(platformTradeDetailSV.listPagePlatformTdDetail(platformTradeDetailModel, pageNo, limit));
	}


	@ApiOperation("平台账户信息")
	@GetMapping(value = "/accountInfo")
	public APIResponse<PlatformAccountEntity> platformAccountInfo() {
		return successData(platformAccountSV.selectById(1L));
	}

	@ApiOperation("平台账户交易明细导出")
	@GetMapping(value = "/tdDetail/export")
	public void exportPlatformTdDetail(HttpServletResponse response,
                                       PlatformTradeDetailParam platformTradeDetailModel
	) throws Exception {
		List<PlatformTradeDetailEntity> list = platformTradeDetailSV.listPlatformTdDetail(platformTradeDetailModel);

		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "平台账户交易明细";
		String[] headerString = {"序号", "交易流水号", "交易明细内容", "交易金额", "交易后账户余额", "交易类型", "现金流向", "交易时间", "创建时间"};
		String[] headerField = {"id", "tradeNo", "tdBody", "tdAmount", "aftTdAmount", "tdTypeName", "cashFlowName", "tdTime", "createTime"};
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}

	@ApiOperation("平台账户交易汇总")
	@GetMapping(value = "/tdDetail/summary")
	public APIResponse<TdDetailSummaryVO> tdDetailSummary(
			@ApiParam(name = "startTime", value = "开始时间")
			@RequestParam(required = false) Date startTime,
			@ApiParam(name = "endTime", value = "结束时间")
			@RequestParam(required = false) Date endTime
	) {
		//消费退费交易汇总
		TdDetailSummaryVO consumeVO = consumeDetailsSV.tdDetailSummary(CashFlowEnum.EXPEND.getKey(), startTime, endTime);
		TdDetailSummaryVO returnVO = consumeDetailsSV.tdDetailSummary(CashFlowEnum.INCOME.getKey(), startTime, endTime);
		//充值体现交易汇总
		TdDetailSummaryVO rechargeVO = transactionDetailsSV.tdDetailSummary(TransactionDetailsTdTypeEnum.RECHARGE.getKey(), startTime, endTime);
		TdDetailSummaryVO withdrawVO = transactionDetailsSV.tdDetailSummary(TransactionDetailsTdTypeEnum.EMBODY.getKey(), startTime, endTime);
		//出账汇总
		TdDetailSummaryVO chargeVO = sysAuditSV.tdDetailSummary(startTime, endTime);

		TdDetailSummaryVO tdDetailSummaryVO = new TdDetailSummaryVO();
		//时间
		if(startTime != null && endTime != null){
			tdDetailSummaryVO.setTimePeroid(startTime+"-"+endTime);
		}

		tdDetailSummaryVO.setConsumeCount(consumeVO.getConsumeCount());
		tdDetailSummaryVO.setConsumeMoney(consumeVO.getConsumeMoney());
		tdDetailSummaryVO.setReturnCount(returnVO.getConsumeCount());
		tdDetailSummaryVO.setReturnMoney(returnVO.getConsumeMoney());
		tdDetailSummaryVO.setRechargeCount(rechargeVO.getRechargeCount());
		tdDetailSummaryVO.setRechargeMoney(rechargeVO.getRechargeMoney());
		tdDetailSummaryVO.setWithdrawCount(withdrawVO.getRechargeCount());
		tdDetailSummaryVO.setWithdrawMoney(withdrawVO.getRechargeMoney());
		tdDetailSummaryVO.setChargeCount(chargeVO.getChargeCount());
		tdDetailSummaryVO.setChargeMoney(chargeVO.getChargeMoney());
		//总计
		tdDetailSummaryVO.setIncomeCount(consumeVO.getConsumeMoney()
				.subtract(returnVO.getConsumeMoney())
				.add(rechargeVO.getRechargeMoney())
				.subtract(withdrawVO.getRechargeMoney())
				.subtract(chargeVO.getChargeMoney()));
		return successData(tdDetailSummaryVO);
	}

	@ApiOperation("平台账户交易汇总导出")
	@GetMapping(value = "/exportTdDetailSummary")
	public void exportTdDetailSummary(
			HttpServletResponse response,
			@ApiParam(name = "startTime", value = "开始时间")
			@RequestParam(required = false) Date startTime,
			@ApiParam(name = "endTime", value = "结束时间")
			@RequestParam(required = false) Date endTime
	) throws Exception {
		TdDetailSummaryVO data = (TdDetailSummaryVO)tdDetailSummary(startTime, endTime).getData();
		List<TdDetailSummaryVO> list = new ArrayList<TdDetailSummaryVO>();
		list.add(data);
		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "平台账户交易汇总";
		String[] headerString = {"对账时间段", "充值笔数","充值金额", "提现笔数", "提现金额", "支付笔数", "支付金额", "退费笔数", "退费金额","出账笔数","出账金额","总收入"};
		String[] headerField = {"timePeroid", "rechargeCount", "rechargeMoney", "withdrawCount", "withdrawMoney", "consumeCount", "consumeMoney", "returnCount","returnMoney",
								"chargeCount","chargeMoney","incomeCount"};
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}

	@ApiOperation("医生消费收入记录")
	@GetMapping(value = "/docIncomeRecord/list")
	public APIResponse<PageInfo<SysAuditParam>> listDocIncomeRecord(
			PlatformAccountExampleParam platformAccountExampleParam,
			@RequestParam(defaultValue = "1") int pageNo,
			@RequestParam int limit
	) {
		if(platformAccountExampleParam.getStartTime() == null || platformAccountExampleParam.getEndTime() == null){
			throw new BusinessException("请传入开始时间和结束时间");
		}
		return successData(sysAuditSV.listPageDocIncomeRecord(platformAccountExampleParam, pageNo, limit));
	}

	@ApiOperation("人工出账")
	@PostMapping(value = "/sysAudit/artificial")
	public APIResponse artificialSysAudit(
			@RequestBody List<SysAuditParam> sysAuditModels
	) {
		Long sysId = ShiroUtil.getLoginId();
		sysAuditSV.artificialSysAudit(sysId, sysAuditModels);
		return successData("人工出账成功");
	}

	@ApiOperation("医生消费收入记录导出")
	@GetMapping(value = "/exportDocIncomeRecord")
	public void exportDocIncomeRecord(
			HttpServletResponse response,
			PlatformAccountExampleParam platformAccountExampleVO,
			@RequestParam(defaultValue = "1") int pageNo,
			@RequestParam int limit
	) throws Exception {
		List<SysAuditParam> list = sysAuditSV.listDocIncomeRecord(platformAccountExampleVO);

		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "平台账户交易明细";
		String[] headerString = {"对账时间段", "提现银行卡号", "医生姓名", "提现金额", "平台抽成金额", "提现手续费", "个人所得税", "实际到账金额"};
		String[] headerField = {"timePeroid", "cardNo", "docRealName", "amount", "drawAmount", "withdrawFee", "incomeTax", "actIncomeAmount"};
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}


	@ApiOperation("系统出账记录展示")
	@GetMapping(value = "/sysAudit/list")
	public APIResponse<PageInfo<SysAuditVo>> listSysAudit(
			PlatformAccountExampleParam platformAccountExampleVO,
			@RequestParam(defaultValue = "1") int pageNo,
			@RequestParam int limit
	) {
		return successData(sysAuditSV.listPageSysAudit(platformAccountExampleVO, pageNo, limit));
	}

	@ApiOperation("系统出账记录导出")
	@GetMapping(value = "/exportSysAudit")
	public void exportSysAudit(
			HttpServletResponse response,
			PlatformAccountExampleParam platformAccountExampleVO
	) throws Exception {
		List<SysAuditVo> list = sysAuditSV.listSysAudit(platformAccountExampleVO);
		ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
		String titleName = "系统出账记录";
		String[] headerString = {"序号", "对账时间段", "提现银行卡号", "医生姓名", "订单编号", "提现金额", "平台抽成金额", "提现手续费", "个人所得税", "实际到账金额", "结算状态", "出账时间", "出账人", "结算时间", "结算人"};
		String[] headerField = {"id", "timePeroid", "cardNo", "docRealName", "tdNo", "amount", "drawAmount", "withdrawFee", "incomeTax", "actIncomeAmount", "settlementStatus", "billingTime", "settlementPerson", "modifyTime", "modifierId"};
		exportExcelUtil.exportExcelForTotal(titleName, headerString, headerField, null, list, response, null);
	}

	@ApiOperation("根据系统出账主键查看抽成明细")
	@GetMapping(value = "/sysDraw/list")
	public APIResponse<List<SysDrawEntity>> listSysDraw(
			@RequestParam Long auditId
	) {
		return successData(sysDrawSV.selectList(TK.select(SysDrawEntity.class).where().andEqualTo(SysDrawEntity::getAuditId,auditId).end()));
	}

	@ApiOperation("出账结算")
	@PostMapping(value = "/sysAudit/settle")
	public APIResponse settleSysAudit(
			@RequestBody Long[] auditIds
	) {
		if (auditIds.length <= 0) {
			throw new BusinessException("请至少选择一个");
		}
		Long sysUserId =ShiroUtil.getLoginId();
		int rows = sysAuditSV.settleSysAudit(auditIds, sysUserId);
		return APIResponse.success("出账结算成功条数", rows);
	}

	@ApiOperation("账单作废")
	@PostMapping(value = "/sysAudit/cancel")
	public APIResponse cancelSysAudit(
			@RequestBody Long[] auditIds
	) {
		if (auditIds.length <= 0) {
			throw new BusinessException("请至少选择一个");
		}
		sysAuditSV.cancelSysAudit(auditIds);
		return success();
	}
}
